package com.junnan.adminbackend.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.junnan.adminbackend.domain.ArkClient;
import com.junnan.adminbackend.domain.ZentaoLogin;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class ZentaoController {

    private final String BASE_URL ="http://60.205.171.41:9780/zentao/api.php/v1";

    /**
     * 创建任务
     */
    @PostMapping(value = "/zentao/executions/create")
    public Object test(@RequestBody JSONObject object) {

        //获取token
        String token = token();
        log.info(token);
        //项目id
        String id = object.getString("stageId");
        String createTaskUrl = BASE_URL + "/executions/" + id + "/tasks";
        return postHttp(object.toJSONString(), createTaskUrl, token);
    }

    /**
     * 创建测试单
     */
    @PostMapping(value = "/zentao/testcases/create")
    public Object testcases(@RequestBody JSONObject object) {

        //获取token
        String token = token();
        log.info(token);
        //项目id
        String id = object.getString("product");
        String createTaskUrl = BASE_URL + "/products/" + id + "/testcases";
        return postHttp(object.toJSONString(), createTaskUrl, token);
    }

    /**
     * 项目列表
     */
    @PostMapping(value = "/zentao/projects")
    public Object projects(@RequestBody ZentaoQuery zentaoQuery) {

        String token = token();
        log.info(token);
        String projectUrl = BASE_URL + "/projects?page=" + zentaoQuery.getPage() + "&limit=" + zentaoQuery.getLimit();
        return getHttp(projectUrl, token);
    }

    @PostMapping(value = "/zentao/stages")
    public Object stages(@RequestBody ZentaoQuery zentaoQuery) {

        String token = token();
        log.info(token);
        String stagesUrl = BASE_URL + "/projects/" + zentaoQuery.getId() + "/executions";
        return getHttp(stagesUrl, token);
    }




    public String token() {
        //获取token
        ZentaoLogin login = new ZentaoLogin("lilu", "1qaz!QAZ");
        String url = BASE_URL + "/tokens";
        Object o = postHttp(JSON.toJSONString(login), url, null);
        JSONObject loginRes = JSONObject.parseObject(o.toString());
        return loginRes.getString("token");
    }

    /**
     * POST请求，json格式可使用该公共方法
     * @param paramJsonStr 请求体json字符串
     * @param url 请求url
     * @return
     */
    public Object postHttp(String paramJsonStr, String url, String token) {

        Map<String, String> headers = new HashMap<>();
        log.info("token:{}", token);
        if (StrUtil.isNotBlank(token)) {
            headers.put("Token", token);
        }

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30,TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .build();


        okhttp3.RequestBody body = okhttp3.RequestBody.create(MediaType.parse("application/json"), paramJsonStr);
        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(headers))
                .post(body)
                .build();
        log.info("调用请求:{},接口入参：{},请求头:{}", url, paramJsonStr, JSON.toJSONString(headers));
        try {
            Response response = client.newCall(request).execute();
            log.info(JSON.toJSONString(response));
            return response.isSuccessful() ? JSON.toJSON(response.body().string()) : null;
        } catch (Exception e) {
            log.error("请求失败", e);
        }
        return null;
    }

    public Object getHttp(String url, String token) {

        Map<String, String> headers = new HashMap<>();
        if (StrUtil.isNotBlank(token)) {
            headers.put("Token", token);
        }

        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30,TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .build();


        Request request = new Request.Builder()
                .url(url)
                .headers(Headers.of(headers))
                .get()
                .build();
        log.info("调用请求:{},接口入参：{},请求头:{}", url, JSON.toJSONString(headers));
        try {
            Response response = client.newCall(request).execute();
            log.info(JSON.toJSONString(response));
            return response.isSuccessful() ? JSON.toJSON(response.body().string()) : null;
        } catch (Exception e) {
            log.error("请求失败", e);
        }
        return null;
    }
}
